package com.biz.primus.ms.oms.dao.redis;

import com.biz.primus.base.redis.util.RedisUtil;
import com.biz.primus.base.redis.util.SimpleDataRedisDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yanweijin
 * @date 2017/11/24
 */
@Repository
@Slf4j
public class FlashOrderMonitoringRedisDao extends SimpleDataRedisDao {

	private static final String flashMonitoringSourceKey="oms:delivery:flashMonitoringSource";

	/**
	 * 将订单id和其expectedTime作为zset的value和score存入redis以待查询
	 * @param orderId
	 * @param expectedTime
	 */
	public void addMonitoringSource(Long orderId, LocalDateTime expectedTime){
		zadd(flashMonitoringSourceKey, Timestamp.valueOf(expectedTime).getTime(), RedisUtil.toByteArray(orderId));
	}

	/**
	 * 取出当前时间已经超过expectedTime的订单id
	 * @return 订单id集合,需要进行业务判断订单是否真正timeout
	 */
	public Set<Long> popTimeoutedSource(){
		long beforeTimestamp = System.currentTimeMillis();
		Set<String> ids = zrangeByScore(flashMonitoringSourceKey, 0, beforeTimestamp);
		log.info("timeoutFlashOrder|before[{}]|ids[{}]",beforeTimestamp,ids);
		zrem(flashMonitoringSourceKey,ids.stream().toArray(String[]::new));
		return ids.stream().map(Long::valueOf).collect(Collectors.toSet());
	}


}
